package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.google.gson.JsonObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    @Value("${wechat.AppID}")
    private String appId;
    @Value("${wechat.AppSecret}")
    private String appSecret;


    /**
     * 获取OpenId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        String result = HttpUtil.get(REQUEST_URL, map);

        JSONObject entries = JSONUtil.parseObj(result);
        if (ObjectUtils.isNotEmpty(entries.getInt("errcode"))) {
            throw new BaseException(entries.getStr("errmsg"));
        }
        return entries.getStr("openid");
    }

    /**
     * 获取手机号
     *
     * @param detailCode
     * @return
     */
    @Override
    public String getPhone(String detailCode) {
        //获取access_token
        String token = getToken();
        String url = PHONE_REQUEST_URL + token;
        Map<String, Object> map = new HashMap<>();
        map.put("code", detailCode);
//获取返回结果
        String post = HttpUtil.post(url, JSONUtil.toJsonStr(map));

        //返回结果转换
        JSONObject entries = JSONUtil.parseObj(post);
//判断是否返货成功
        if (!entries.getInt("errcode").equals(0)) {
            throw new BaseException(entries.getStr("errmsg"));
        }

        return entries.getJSONObject("phone_info").getStr( "purePhoneNumber");
    }

    private String getToken() {
        Map<String, Object> param = new HashMap<>();

        param.put("appid", appId);
        param.put("secret", appSecret);

        String result = HttpUtil.get(TOKEN_URL, param);

        JSONObject entries = JSONUtil.parseObj(result);

        return entries.getStr("access_token");
    }
}
